﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Path = System.IO.Path;
using ScriptBox.Services;

namespace ScriptBox
{
    /// <summary>
    /// Window_DbcBalance.xaml 的交互逻辑
    /// </summary>
    // 在类顶部确保实现INotifyPropertyChanged接口
    public partial class Window_DbcBalance : Window, INotifyPropertyChanged
    {
        // 添加时间槽模式枚举
        public enum TimeSlotMode { FiveMS, TenMS }
        
        private TimeSlotMode _selectedTimeSlot = TimeSlotMode.FiveMS;
        public TimeSlotMode SelectedTimeSlot
        {
            get => _selectedTimeSlot;
            set
            {
                _selectedTimeSlot = value;
                OnPropertyChanged();
            }
        }

        private ObservableCollection<string> _filePaths = new ObservableCollection<string>();

        public ObservableCollection<string> FilePaths
        {
            get => _filePaths;
            set
            {
                _filePaths = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(HasFiles));
                OnPropertyChanged(nameof(FileCount));
            }
        }

        public bool HasFiles => FilePaths.Any();
        public string FileCount => FilePaths.Count.ToString();
        
        public Window_DbcBalance()
        {
            InitializeComponent();
            DataContext = this;
            InitializeDropHandlers();
        }

        private void InitializeDropHandlers()
        {
            DropZone.AllowDrop = true;
            const string validExtension = ".dbc";

            DropZone.DragEnter += (s, e) =>
            {
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    var files = (string[])e.Data.GetData(DataFormats.FileDrop);
                    var invalidFiles = files
                        .Where(f => !Path.GetExtension(f).Equals(validExtension, StringComparison.OrdinalIgnoreCase))
                        .Count();

                    if (invalidFiles == 0)
                    {
                        StatusText.Text = "释放鼠标导入.dbc文件";
                        DropZone.Background = Brushes.LightGreen;
                        e.Effects = DragDropEffects.Copy;
                    }
                    else
                    {
                        StatusText.Text = $"包含 {invalidFiles} 个非.dbc文件";
                        DropZone.Background = Brushes.LightPink;
                        e.Effects = DragDropEffects.None;
                    }
                }
                else
                {
                    StatusText.Text = "仅支持文件拖放操作";
                    DropZone.Background = Brushes.LightPink;
                    e.Effects = DragDropEffects.None;
                }
            };

            DropZone.Drop += (s, e) =>
            {
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    var files = ((string[])e.Data.GetData(DataFormats.FileDrop))
                        .Where(f => Path.GetExtension(f).Equals(validExtension, StringComparison.OrdinalIgnoreCase))
                        .Distinct()
                        .ToList();

                    if (files.Count > 0)
                    {
                        // 修改集合更新方式
                        FilePaths.Clear();
                        foreach (var file in files)
                        {
                            FilePaths.Add(file);
                        }
                        
                        StatusText.Text = $"已选择 {files.Count} 个.dbc文件";
                        // 添加双重通知
                        OnPropertyChanged(nameof(FilePaths));
                        OnPropertyChanged(nameof(HasFiles));
                    }
                }
                DropZone.Background = new SolidColorBrush(Color.FromRgb(240, 240, 240));
            };
        }

        private void ConvertButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var successCount = 0;
                foreach (var filePath in FilePaths)
                {
                    if (!File.Exists(filePath)) continue;

                    ProcessFile(filePath);
                    successCount++;
                }

                StatusText.Text = $"成功转换 {successCount}/{FilePaths.Count} 个文件，输出文件与原始文件同目录";
            }
            catch (Exception ex)
            {
                StatusText.Text = $"转换出错：{ex.Message}";
            }
        }

        // 修改方法签名和实现
        private void ProcessFile(string inputPath)
        {
            try
            {
                // 根据选择的时间槽创建处理器
                var processor = new DBCProcessor(inputPath, 
                    SelectedTimeSlot == TimeSlotMode.FiveMS ? 5 : 10);
                processor.ProcessFile(out string outputPath, out string reportPath);
                
                if (!File.Exists(outputPath) || !File.Exists(reportPath))
                {
                    StatusText.Text = $"文件生成失败：{inputPath}";
                }
            }
            catch (Exception ex)
            {
                StatusText.Text = $"处理失败：{inputPath}\n错误信息：{ex.Message}";
            }
        }

        private void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            FilePaths.Clear();
            StatusText.Text = "文件列表已清空";
        }

        // INotifyPropertyChanged 实现
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "") // 参数改为空字符串默认值
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        
        // 添加RadioButton绑定
        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is RadioButton radio)
            {
                if (radio.Content.ToString() == "5ms")
                    SelectedTimeSlot = TimeSlotMode.FiveMS;
                else if (radio.Content.ToString() == "10ms")
                    SelectedTimeSlot = TimeSlotMode.TenMS;
            }
        }
    }
}
